package com.model.dao.base.impl;

import java.lang.reflect.Type;
import java.util.List;
import java.lang.reflect.ParameterizedType; 

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.stereotype.Repository;

import com.model.dao.base.BaseDao;
import com.model.dao.base.SessionFactoryUtil;

@Repository("baseDao")
public class BaseDaoImpl<T> extends SessionFactoryUtil  implements BaseDao<T> {

	private Session session;

	public BaseDaoImpl() {
	
	}

	
	
	@Override
	public void save(T t) {
		getSession().save(t);
		closeSession();
	}

	@Override
	public void update(T t) {
		getSession().clear();
		getSession().update(t);
		flush();
		closeSession();
	}

	@Override
	public void delete(T t) {
		getSession().delete(t);
		closeSession();
	}

	


	@Override
	public List<T> QueryList(Class<T> t,Object[] objects) {
		
       return null;
	}

	@SuppressWarnings("unchecked")
	@Override
	public T QueryById(Class<T> t,int id) {
		return  (T) getSession().get(t, id);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<T> QueryBySqlList(String sql, Object[] args,Class<T> entityClass) {
		Query q = this.getSession().createSQLQuery(sql).addEntity(entityClass);
		if (args != null) {
			for (int i = 0; i < args.length; i++) {
				q.setParameter(i, args[i]);
			}
		}
		List<T> list  = (List<T>) q.list();	
		closeSession();
	
       return list;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<T> QueryByHqlList(String hql, Object[] args) {

		Query q = this.getSession().createQuery(hql);
			if (args != null) {
				for (int i = 0; i < args.length; i++) {
					q.setParameter(i, args[i]);
				}
			}
			List<T> list  = (List<T>) q.list();
			closeSession();
           return list;
	}

	@Override
	public int getAllRowCount(String hql, Object[] args) {
		return QueryByHqlList(hql, args).size();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<T> queryForPage(int offset, int length, String hql,Object[] args) {
		Query q = this.getSession().createQuery(hql);
		if (args != null) {
			for (int i = 0; i < args.length; i++) {
				q.setParameter(i, args[i]);
			}
		}
		q.setFirstResult(offset); // 当前页数
		q.setMaxResults(length); // 每页显示的记录数
				List<T> list  = (List<T>) q.list();	
				closeSession();
	return list;
	}

	@Override
	public void flush() {
		if(session!=null){
			session.flush();
		}
		
	}

	/**
	 * 获取session
	 * 
	 * @return
	 */
	public Session getSession() {

	  if(session==null){
		  session = sessionFactory.openSession();
	  }
	  return session;
	}

	/**
	 * 关闭session
	 */
	public void closeSession() {
		if(session.isOpen()){
			session.close();
			session = null;
		}
		
	}

}



